<template>
  <template>
    <vxe-column v-if="isShowBuildInDeleteRow" :title="''" width="40" fixed="left">
      <template #default="{ row, rowIndex, columnIndex }">
        <GdIcon
          :icon-name="'remove'"
          class="table-row-remove-icon"
          @click="onRemoveTableRow({ row, rowIdx: rowIndex })"
        ></GdIcon>
      </template>
    </vxe-column>
    <vxe-column
      v-if="isShowExclusiveColBuildInCheckbox"
      type="checkbox"
      width="60"
      :tree-node="isTreeNode(tableCommonAttr, 'buildInCheckbox')"
      fixed="left"
    ></vxe-column>
    <vxe-column
      v-if="isShowBuildInSeq"
      type="seq"
      title="序号"
      width="60"
      :tree-node="isTreeNode(tableCommonAttr, 'buildInSeq')"
      fixed="left"
    ></vxe-column>
    <template v-for="metaItem in tableColMetaList" :key="metaItem.key">
      <template v-if="metaItem?.isShow ?? true">
        <vxe-column
          v-if="isEditRender(metaItem)"
          :field="metaItem.key"
          :title="metaItem.label"
          :tree-node="isTreeNode(tableCommonAttr, metaItem.key)"
          :edit-render="{}"
        >
          <template #default="{ row, rowIndex, columnIndex }">
            <span v-if="['Text', 'RichText'].includes(metaItem.type)">
              {{ row[metaItem.key] }}
            </span>
            <DimensionItemContent
              v-else
              :key="metaItem.key + rowIndex"
              :meta-item="metaItem"
              :common-attr="tableCommonAttr"
              :row-idx="rowIndex"
              :col-idx="columnIndex"
              :row-data="row"
              :table-body-data="tableBodyData"
              :item-submit-config="tableCellSubmitConfig"
              :meta-dynmic-config="getMetaDynmicConfig(metaItem)"
              :cell-force-meta-config-mapping="cellForceMetaConfigMapping"
              :vm-template-config="editConfig.vmTemplateConfig"
              v-bind="$attrs"
            ></DimensionItemContent>
          </template>
          <template #edit="{ row, rowIndex, columnIndex }">
            <DimensionItemContent
              :key="metaItem.key + rowIndex"
              :meta-item="metaItem"
              :common-attr="tableCommonAttr"
              :row-idx="rowIndex"
              :col-idx="columnIndex"
              :row-data="row"
              :table-body-data="tableBodyData"
              :item-submit-config="tableCellSubmitConfig"
              :meta-dynmic-config="getMetaDynmicConfig(metaItem)"
              :cell-force-meta-config-mapping="cellForceMetaConfigMapping"
              :vm-template-config="editConfig.vmTemplateConfig"
              v-bind="$attrs"
            ></DimensionItemContent>
          </template>
        </vxe-column>
        <vxe-column
          v-else
          :field="metaItem.key"
          :title="metaItem.label"
          :tree-node="isTreeNode(tableCommonAttr, metaItem.key)"
          :width="getColumnWidth(metaItem)"
          :type="getBuildInColumnType(tableCommonAttr, metaItem.key)"
        >
          <template #default="{ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex, _columnIndex }">
            <TableCellItemContent
              :metaItem="metaItem"
              :meta-item-list="tableColMetaList"
              :common-attr="tableCommonAttr"
              :row-data="row"
              :row-idx="rowIndex"
              :col-idx="columnIndex"
              :table-row-index="$rowIndex"
              :table-column-index="$columnIndex"
              :table-body-data="tableBodyData"
              :item-submit-config="tableCellSubmitConfig"
              :meta-dynmic-config="getMetaDynmicConfig(metaItem)"
              :cell-force-meta-config-mapping="cellForceMetaConfigMapping"
              :vm-template-config="editConfig.vmTemplateConfig"
              v-bind="$attrs"
            ></TableCellItemContent>
          </template>
          <template #content="{ row, rowIndex, columnIndex }">
            <view style="height: auto">
              <scene-container-table-form
                :ancestor-table-common-attr="ancestorTableCommonAttr"
                :table-common-attr="getMergedMomChildTableCommonAttr()"
                :table-col-meta-list="tableColMetaList"
                :table-body-data="row['_gd_buildInExpandData']"
                :table-loading="false"
                :searchFormItemMetaList="[]"
                :tool-bar-config="{ buttons: [] }"
                :operation-btns-config="{ buttons: [] }"
                :all-btns-emit-form-item-meta-config="{}"
                v-bind="$attrs"
                @checkboxChange="onChildCheckboxChange"
              ></scene-container-table-form>
            </view>
          </template>
        </vxe-column>
      </template>
    </template>
    <OperationBtns
      ref="operationBtnsRef"
      v-if="isShowOperationBtns"
      :operation-btns-config="operationBtnsConfig"
      :table-col-meta-list="tableColMetaList"
      :table-body-data="tableBodyData"
      :is-tree-table="isTreeTable"
      :edit-config="editConfig"
      :cell-force-meta-config-mapping="cellForceMetaConfigMapping"
      @do-operation="(params) => emits('do-operation', params)"
    ></OperationBtns>
  </template>
</template>
<script>
  export default {
    inheritAttrs: false,
  };
</script>
<script setup>
  import { ref, watch, computed } from "vue";
  import { cloneDeep } from "@gd-accbuild-core/config/utils";
  import OperationBtns from "./components/operation-btns/index.vue";
  import DimensionItemContent from "@gd-accbuild-ui/dimension-ui/dimension-item-content/dimension-item-content.vue";
  import { isTreeNode, getBuildInColumnType } from "../../hooks/useConfigTrans";
  import { useGetTableColumnWidth } from "./hooks/useGetTableColumnWidth";
  import GdIcon from "@gd-accbuild-ui/gd-ui/gd-icon/gd-icon.vue";
  import TableCellItemContent from "./table-cell-item-content.vue";
  const props = defineProps({
    tableCommonAttr: {
      type: Object,
      default: () => ({}),
    },
    tableColMetaList: {
      type: Array,
      default: () => [],
    },
    tableBodyData: {
      type: Array,
      default: () => [],
    },
    operationBtnsConfig: {
      type: Object,
    },
    isTreeTable: {
      type: Boolean,
    },
    editConfig: {
      type: Object,
      //default: {},
    },
    tableCellSubmitConfig: {
      type: Object,
    },
    ////////////
    tableColumnDynmicConfigList: {
      type: Array,
    },
    cellForceMetaConfigMapping: {
      type: Object,
    },
    ////////////
    ancestorTableCommonAttr: {
      type: Object,
    },
  });
  const onChildCheckboxChange = (params) => {
    emits("checkboxChange", params);
  };

  const isShowBuildInDeleteRow = computed(() => {
    return (
      props.tableCommonAttr?.editConfig?.buildInDeleteRowConfig?.isShow ??
      props.tableCommonAttr?.editConfig?.editableStyle === "Inline"
    );
  });

  /**
   * 是否显示独占一列的多选组件
   */
  const isShowExclusiveColBuildInCheckbox = computed(() => {
    return (
      (props.tableCommonAttr?.buildInColumnConfig?.buildInCheckbox?.isShow ?? true) &&
      [undefined, null, ""].includes(props.tableCommonAttr?.buildInColumnConfig?.buildInCheckbox?.config?.labelField)
    );
  });
  const isShowBuildInSeq = computed(() => {
    return props.tableCommonAttr?.buildInColumnConfig?.buildInSeq?.isShow ?? true;
  });
  const isShowOperationBtns = computed(() => {
    return (
      Array.isArray(props.operationBtnsConfig?.buttons) &&
      props.operationBtnsConfig.buttons.length > 0 &&
      props.operationBtnsConfig.buttons.some((btn) => btn?.isShow ?? true)
    );
  });
  /**
   * 获取合并后的母子表的tableCommonAttr
   */
  const getMergedMomChildTableCommonAttr = () => {
    const momTableCommonAttr = cloneDeep(props.tableCommonAttr);
    const overrideTableCommonAttr = momTableCommonAttr.buildInColumnConfig.buildInExpand?.overrideTableCommonAttr ?? {};
    if (momTableCommonAttr.buildInColumnConfig.buildInExpand?.isInheritMomTableCommonAttr ?? true) {
      //TODO:FIXME: 目前暂时只会覆盖子表高度
      if (overrideTableCommonAttr?.tableContentContainerConfig?.height) {
        if (!momTableCommonAttr.hasOwnProperty("tableContentContainerConfig")) {
          momTableCommonAttr.tableContentContainerConfig = {};
        }
        momTableCommonAttr.tableContentContainerConfig.height =
          overrideTableCommonAttr.tableContentContainerConfig.height;
      }
      //TODO:FIXME: 目前暂时只会覆盖子表buildInCheckbox配置
      else if (overrideTableCommonAttr?.buildInColumnConfig?.buildInCheckbox) {
        momTableCommonAttr.buildInColumnConfig.buildInCheckbox =
          overrideTableCommonAttr.buildInColumnConfig.buildInCheckbox;
      }
      momTableCommonAttr.level = overrideTableCommonAttr.level;
      return momTableCommonAttr;
    } else {
      return props.tableCommonAttr.buildInColumnConfig.buildInExpand?.overrideTableCommonAttr ?? {};
    }
  };
  const emits = defineEmits(["do-operation", "remove-table-row", "checkboxChange"]);
  const isEditRender = (metaItem) => {
    return metaItem.type.indexOf("Text") === -1 || props.tableCommonAttr?.editConfig?.editableStyle === "Inline";
  };

  const onRemoveTableRow = ({ row, rowIdx }) => {
    console.log("移除行", rowIdx);
    emits("remove-table-row", { rowData: row, rowIdx });
  };
  /**
   * 计算列宽度：按中英文设置 不同宽度
   */
  const getColumnWidth = (curMetaData) => useGetTableColumnWidth(curMetaData, props.tableBodyData);

  /**
   * 获取动态元数据配置
   */
  const getMetaDynmicConfig = (metaItem) => {
    if (!Array.isArray(props.tableColumnDynmicConfigList)) {
      return { key: metaItem.key };
    }
    const matchedConfig = props.tableColumnDynmicConfigList.find((config) => config.key === metaItem.key);
    if (!matchedConfig) {
      return { key: metaItem.key };
    } else {
      return matchedConfig;
    }
  };
  const cellForceMetaConfigMappingKeys = computed(() => {
    return Object.keys(props.cellForceMetaConfigMapping);
  });
  const curActivedRowKeys = computed(() => {
    return cellForceMetaConfigMappingKeys.value.map((el) => el.split(";")[0]);
  });

  const operationBtnsRef = ref(null);
  defineExpose({
    operationBtnsRef: operationBtnsRef,
  });
</script>
<style lang="scss">
  .table-row-remove-icon:hover {
    color: orange;
    cursor: pointer;
  }
</style>
